﻿namespace Blaze.Editor.EditorExtensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using UnityEngine;

    /// <summary>
    /// 用于控制Project上的显示。
    /// </summary>
    public class ProjectWindowExtension
    {
        /// <summary>
        /// 获取所有组件列表。
        /// </summary>
        public static List<ProjectComponent> Components { get; private set; }

        public ProjectWindowExtension()
        {
            Components = getComponents<ProjectComponent>().ToList();
        }

        public void ProjectWindowItemOnGUIHandler(string guid, Rect selectionRect)
        {
            if (Event.current.type != EventType.Repaint)
                return;

            var rect = new Rect(selectionRect);
            foreach (var component in Components)
            {
                if (!component.IsEnabled)
                    continue;

                component.Initialize();
                if (!component.Validate(guid))
                    continue;
                if (!component.Layout(guid, ref rect))
                    continue;

                var originalColor = GUI.color;
                var originalContentColor = GUI.contentColor;
                var originalBackgroundColor = GUI.backgroundColor;
                component.Draw(guid, selectionRect);
                GUI.color = originalColor;
                GUI.contentColor = originalContentColor;
                GUI.backgroundColor = originalBackgroundColor;
            }
        }

        private static IEnumerable<T> getComponents<T>() where T : new()
        {
            var componentType = typeof (T);
            var query = from type in Assembly.GetExecutingAssembly().GetTypes()
                where componentType.IsAssignableFrom(type) && !type.IsAbstract
                select (T) Activator.CreateInstance(type);
            return query;
        }
    }
}